package org.tea.inventory.admin.web.warehouse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import io.swagger.annotations.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.tea.inventory.admin.web.admin.BaseController;
import org.tea.inventory.base.response.BaseResponse;
import org.tea.inventory.base.util.ResponseUtil;
import org.tea.inventory.base.util.StringUtils;
import org.tea.inventory.base.util.excel.ExportExcel;
import org.tea.inventory.base.validation.groups.warehouse.RequisitionGroup;
import org.tea.inventory.domain.tea.Product;
import org.tea.inventory.domain.tea.WarehouseInventorySerialInfo;
import org.tea.inventory.model.vo.WarehouseInventorySerialVo;
import org.tea.inventory.service.IWarehouseInventorySerialService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 调拨单 Controller
 * 
 * @author dongxb
 * @date 2025-04-23
 */
@Api(tags = "库存-调拨单控制器")
@Slf4j
@RestController
@RequestMapping("/admin/warehouse-requisition")
@RequiredArgsConstructor
public class WarehouseRequisitionController extends BaseController
{
    @Autowired
    private IWarehouseInventorySerialService warehouseInventorySerialService;

    /**
     * 查询调拨单列表
     */
    @GetMapping("page")
    @ApiOperation(value = "查询调拨单列表")
    @ApiResponses(
            @ApiResponse(code = 0, message = "成功", response = Product.class)
    )
    public BaseResponse page(WarehouseInventorySerialVo warehouseInventorySerialVo)
    {
        startPage();
        warehouseInventorySerialVo.setSerialType("3");
        List<WarehouseInventorySerialVo> list = warehouseInventorySerialService.selectWarehouseInventorySerialList(warehouseInventorySerialVo);
        return getDataTable(list);
    }


    /**
     * 导出调拨单列表
     */
    @GetMapping("/export")
    @ApiOperation(value = "导出调拨单列表")
    public void exportWarehouseInventorySerialVo(WarehouseInventorySerialVo warehouseInventorySerialVo, HttpServletRequest request, HttpServletResponse response) {
        warehouseInventorySerialVo.setSerialType("3");

        Map<String, Object> map = new HashMap<>();
        String title = "调拨单列表";
        String header = "调拨单号,调拨时间,调出仓库,调出经手人,调入仓库,调入经手人,调拨状态";
        String column = "serialCode,serialDateStr,warehouseName,outHandlerName,warehouseTargetName,addHandlerName,isRunFinishStr";
        map.put("biaoti", title);
        map.put("header", header);
        map.put("column", column);
        try {
            List<WarehouseInventorySerialVo> productCategories = warehouseInventorySerialService.selectWarehouseInventorySerialList(warehouseInventorySerialVo);
            List<Map> list = JSONArray.parseArray(JSON.toJSONString(productCategories), Map.class);
            ExportExcel.export(request, response, list, map);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取调拨单详细信息
     */
    @GetMapping("/info")
    @ApiOperation(value = "获取调拨单详细信息")
    public BaseResponse getInfo(Long id)
    {
        return ResponseUtil.ok(warehouseInventorySerialService.selectWarehouseInventorySerialById(id));
    }

    /**
     * 新增调拨单
     */
    @PostMapping(value = "/add")
    @ApiOperation(value = "新增调拨单")
    public BaseResponse add(@Validated({RequisitionGroup.class}) @RequestBody WarehouseInventorySerialVo warehouseInventorySerialVo)
    {
        log.info("add requisition warehouseInventorySerialVo=" + warehouseInventorySerialVo);
        //校验出入库仓库是否为同一个，如果同一个则无法新增调拨单
        if (warehouseInventorySerialVo.getWarehouseId().equals(warehouseInventorySerialVo.getWarehouseTargetId())) return ResponseUtil.fail(-1 , "调出仓库和调出仓库不能是同一个仓库，无法新增调拨单");

        //校验出库数量是否大于库存数量，如果大于则无法新增调拨单
        if (checkInventory(warehouseInventorySerialVo)) return ResponseUtil.fail(-1 , "出库数量大于当前库存数量，无法新增调拨单");
        //将流水类型赋值为3 调拨单
        warehouseInventorySerialVo.setSerialType("3");
        return ResponseUtil.ok(warehouseInventorySerialService.insertWarehouseInventorySerial(warehouseInventorySerialVo));
    }

    /**
     * 校验出库数量是否大于库存数量
     * @param warehouseInventorySerialVo
     * @return
     */
    public boolean checkInventory(WarehouseInventorySerialVo warehouseInventorySerialVo){
        List<WarehouseInventorySerialInfo> entrys = warehouseInventorySerialVo.getInventoryEntryInfos();
        for (WarehouseInventorySerialInfo ent : entrys) {
            if (ent.getCreateProductNumber() < ent.getUpdateNumber()) return true;
        }
        return false;
    }

    /**
     * 执行仓库管理单
     */
    @PostMapping(value = "/execute")
    @ApiOperation(value = "执行调拨单")
    public BaseResponse execute(@ApiParam(value = "调拨单id集合") Long[] ids)
    {
        return ResponseUtil.ok(warehouseInventorySerialService.execute(ids));
    }

    /**
     * 作废调拨单
     */
    @PostMapping(value = "/cancel")
    @ApiOperation(value = "作废调拨单")
    public BaseResponse cancel(@ApiParam(value = "作废调拨单id") Long id ,@ApiParam(value = "作废原因") String cancelMsg)
    {
        if (StringUtils.isBlank(cancelMsg)) {
            return ResponseUtil.fail(-1,"作废失败，作废原因不能为空");
        }
        return ResponseUtil.ok(warehouseInventorySerialService.cancel(id , cancelMsg));
    }

    /**
     * 修改调拨单
     */
    @PostMapping(value = "/edit")
    @ApiOperation(value = "修改调拨单")
    public BaseResponse edit(@Validated({RequisitionGroup.class}) @RequestBody WarehouseInventorySerialVo warehouseInventorySerialVo)
    {
        return ResponseUtil.ok(warehouseInventorySerialService.updateWarehouseInventorySerial(warehouseInventorySerialVo));
    }

    /**
     * 删除调拨单
     */
    @PostMapping(value = "/remove")
    @ApiOperation(value = "删除调拨单")
    public BaseResponse remove(@ApiParam(value = "删除调拨单id集合") Long[] ids)
    {
        return ResponseUtil.ok(warehouseInventorySerialService.deleteWarehouseInventorySerialByIds(ids));
    }
}
